/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include <boost/date_time/posix_time/posix_time.hpp>

#include "Xern/IInputSystem.hpp"
#include "Xern/IPhysicsEngine.hpp"
#include "Xern/IResourceCache.hpp"
#include "Xern/ISoundEngine.hpp"
#include "Xern/IClientModule.hpp"
#include "Xern/IServerModule.hpp"

#include "Xern/Exceptions.hpp"
#include "Xern/Engine.hpp"
#include "Xern/PluginRegistry.hpp"
#include "Xern/ResourceManager.hpp"
#include "Xern/WorldManager.hpp"
#include "Xern/Console.hpp"

namespace Xern
{
	Engine::Engine()
	{
		closing = false;

		// Create the master console and the plugin registry.
		masterConsole.reset(new Console());
		pluginRegistry.reset(new PluginRegistry());
	}

	Engine::~Engine()
	{
	}

	void Engine::Initialize()
	{
		// Create the resource manager.
		resourceManager.reset(new ResourceManager());

		// Create the world manager.
		worldManager.reset(new WorldManager());

		// Load the plugins.
		pluginRegistry->LoadPlugins();
		resourceManager->LoadPlugins();
	}

	const SystemDescription &Engine::GetSystemDescription() const
	{
		return systemDescription;
	}

	void Engine::ConfigDefaults()
	{
		// Set the defaults.
		if(systemDescription.renderer.empty())
			systemDescription.renderer = "OgreRenderer";

		if(systemDescription.inputSystem.empty())
			systemDescription.inputSystem = "OISInputSystem";

		if(systemDescription.physicsEngine.empty())
			systemDescription.physicsEngine = "BulletPhysics";

		if(systemDescription.resourceCache.empty())
			systemDescription.resourceCache = "SqliteCache";

		if(systemDescription.soundEngine.empty())
			systemDescription.soundEngine = "OpenAL";

		if(systemDescription.scriptEngine.empty())
			systemDescription.scriptEngine = "SquirrelScript";

		if(systemDescription.guiSystem.empty())
			systemDescription.guiSystem = "MyGUI";

		if(systemDescription.clientModule.empty())
			systemDescription.clientModule = "XernClient";

		if(systemDescription.serverModule.empty())
			systemDescription.serverModule= "XernServer";
	}

	void Engine::OpenEngine(const SystemDescription &sysdec)
	{
		// Store a copy.
		systemDescription = sysdec;

		// Configure defaults.
		ConfigDefaults();

		// Get the renderer.
		if(systemDescription.renderer != "None")
		{
			renderer = pluginRegistry->QueryInterface<IRenderer> ("Renderer", systemDescription.renderer);
			if(!renderer)
				throw XernException("Failed to load the renderer " + systemDescription.renderer);
		}

		// Get the input system.
		if(systemDescription.inputSystem != "None")
		{
			inputSystem = pluginRegistry->QueryInterface<IInputSystem> ("Input", systemDescription.inputSystem);
			if(!inputSystem)
				throw XernException("Failed to load the input system " + systemDescription.inputSystem);
		}

		// Get the physics engine.
		if(systemDescription.physicsEngine != "None")
		{
			physicsEngine = pluginRegistry->QueryInterface<IPhysicsEngine> ("Physics", systemDescription.physicsEngine);
			if(!physicsEngine)
				throw XernException("Failed to load the physics engine " + systemDescription.physicsEngine);
		}

		// Get the resource cache  and load it (optional)
		boost::shared_ptr<IResourceCache> resourceCache;
		if(systemDescription.resourceCache != "None")
		{
			resourceCache = pluginRegistry->QueryInterface<IResourceCache> ("ResourceCache", systemDescription.resourceCache);
			if(resourceCache)
				resourceManager->SetResourceCache(resourceCache);
		}

		// Get the script engine.
		if(systemDescription.scriptEngine != "None")
		{
			scriptEngine = pluginRegistry->QueryInterface<IScriptEngine> ("Scripting", systemDescription.scriptEngine);
			if(!scriptEngine)
				throw XernException("Failed to load the script engine " + systemDescription.scriptEngine);
		}

		// Get the sound engine.
		if(systemDescription.soundEngine != "None")
		{
			soundEngine = pluginRegistry->QueryInterface<ISoundEngine> ("Sound", systemDescription.soundEngine);
			if(!soundEngine)
				throw XernException("Failed to load the sound engine " + systemDescription.soundEngine);
		}

		// Get the (optional) gui system.
		if(systemDescription.renderer != "None")
			guiSystem = pluginRegistry->QueryInterface<IGuiSystem> ("GUI", systemDescription.guiSystem);

		// Try to load the client and server modules(optional).
		if(systemDescription.clientModule != "None")
			clientModule = pluginRegistry->QueryInterface<IClientModule> ("Client", systemDescription.clientModule);

		if(systemDescription.serverModule != "None")
			serverModule = pluginRegistry->QueryInterface<IServerModule> ("Server", systemDescription.serverModule);

		// Initialize the renderer.
		if(renderer)
			renderer->Initialize();

		// Initialize the sound engine.
		if(soundEngine)
			soundEngine->Initialize();

		// Notify the world manager of the renderer.
		if(renderer)
			worldManager->OnLoadRenderer(renderer);

		// Initialize the gui system.
		if(guiSystem)
			guiSystem->Initialize();

		// Initialize the input system.
		if(inputSystem)
			inputSystem->Initialize();

		// Initialize the script engine.
		if(scriptEngine)
			scriptEngine->Initialize();

		// Initialize the client.
		if(clientModule)
			clientModule->Initialize();

		// Initialize the server.
		if(serverModule)
			serverModule->Initialize();

		// Reset the closing flag.
		closing = false;
	}

	void Engine::CloseEngine()
	{
		closing = true;
	}

	const posix_time::ptime &Engine::GetCurrentTime() const
	{
		return currentTime;
	}

	void Engine::MainLoop()
	{
		// Reset the clock.
		currentTime = posix_time::microsec_clock::universal_time();
		posix_time::ptime oldTime = currentTime;

		while(true)
		{
			// Get the new time.
			currentTime = posix_time::microsec_clock::universal_time();

			// Calculate the delta time in seconds
			posix_time::time_duration interval = currentTime - oldTime;
			float delta = double(interval.total_milliseconds()) * 0.001;

			// Update the old time.
			if(CompareFloat(delta, 0.0f) != 0)
				oldTime = currentTime;
			else
				delta = 0.0f;

			if(!MainLoopIteration(delta))
				break;

			// Limit fps
			boost::this_thread::sleep(boost::posix_time::milliseconds(5) - interval);
		}
	}

	bool Engine::MainLoopIteration(float delta)
	{
		if(closing)
			return false;

		if(serverModule)
			serverModule->Frame(delta);

		if(clientModule)
			clientModule->Frame(delta);

		if(renderer && !renderer->RenderFrame(delta))
			return false;

		return true;
	}

	void Engine::Shutdown()
	{
		// Shutdown the server.
		if(serverModule)
			serverModule->Shutdown();

		// Shutdown the client.
		if(clientModule)
			clientModule->Shutdown();

		// Shutdown the script engine.
		if(scriptEngine)
			scriptEngine->Shutdown();

		// Shutdown the sound engine.
		if(soundEngine)
			soundEngine->Shutdown();

		// Shutdown the renderer.
		if(renderer)
			renderer->Shutdown();

		// Shutdown the resource manager.
		if(resourceManager)
			resourceManager->Shutdown();

		// Unload the plugins.
		pluginRegistry->UnloadPlugins();
	}

	boost::shared_ptr<PluginRegistry> Engine::GetPluginRegistry()
	{
		return pluginRegistry;
	}

	boost::shared_ptr<WorldManager> Engine::GetWorldManager()
	{
		return worldManager;
	}

	boost::shared_ptr<ResourceManager> Engine::GetResourceManager()
	{
		return resourceManager;
	}

	boost::shared_ptr<IRenderer> Engine::GetRenderer()
	{
		return renderer;
	}

	boost::shared_ptr<IInputSystem> Engine::GetInputSystem()
	{
		return inputSystem;
	}

	boost::shared_ptr<IPhysicsEngine> Engine::GetPhysicsEngine()
	{
		return physicsEngine;
	}

	boost::shared_ptr<ISoundEngine> Engine::GetSoundEngine()
	{
		return soundEngine;
	}

	boost::shared_ptr<IScriptEngine> Engine::GetScriptEngine()
	{
		return scriptEngine;
	}

	boost::shared_ptr<IGuiSystem> Engine::GetGuiSystem()
	{
		return guiSystem;
	}

	boost::shared_ptr<IConsole> Engine::GetMasterConsole()
	{
		return masterConsole;
	}

	boost::shared_ptr<IClientModule> Engine::GetClientModule()
	{
		return clientModule;
	}

	boost::shared_ptr<IServerModule> Engine::GetServerModule()
	{
		return serverModule;
	}

}; // namespace Xern

